package br.com.treinar.jsf;

import javax.faces.component.UIComponent;
import javax.faces.context.FacesContext;
import javax.faces.convert.Converter;
import javax.faces.convert.FacesConverter;

import br.com.treinar.modelo.Telefone;

@FacesConverter("br.com.treinar.TelefoneConverter")
public class TelefoneConverter implements Converter {

	@Override
	public Object getAsObject(FacesContext context, UIComponent component, String object) {
		Telefone telefone = null;
		if (object != null && object.length() == 13) {
			telefone = new Telefone();
			telefone.setDdd(Integer.parseInt(object.substring(1, 3)));
			String numeroStr = object.substring(4, 8) + object.substring(9, object.length());
			telefone.setNumero(Integer.parseInt(numeroStr));
		}
		return telefone;
	}

	@Override
	public String getAsString(FacesContext context, UIComponent component, Object object) {
		Telefone telefone = (Telefone) object;
		
		String telefoneStr = telefone != null && telefone.getNumero() != null ? telefone.getNumero().toString() : null;
		return telefoneStr != null ? "(" + telefone.getDdd() + ")" + telefoneStr.substring(0, 4) + "-" + telefoneStr.substring(4, telefoneStr.length()) : "";
	}

}
